import { Modal } from 'antd';
import { FC, useEffect, useState } from 'react';
import TableRenger from '@/biz-components/table-render';
import { Field } from 'schema-form';
import { getPageMeta } from '@/services/request/meta';
import { getMetaSorted } from '@/components/schema-form-render/until';
import { xhrPostJson } from '@/services';

import './index.less';

interface HistoryModalProps {
    title: string;
    pageApi: string;
    queryKeys: any;
    visible: boolean;
    onCancel: () => void;
}

const HistoryModal: FC<HistoryModalProps> = ({
    title,
    pageApi,
    queryKeys,
    visible,
    onCancel
}) => {
    const [dataSource, setDataSource] = useState<any>();
    const [loading, setLoading] = useState(false);
    const [columns, setColumns] = useState<Field[]>();

    useEffect(() => {
        initTableColumns();
    }, [])

    useEffect(() => {
        setDataSource([]);
        handleSearch(1, 10);
    }, [JSON.stringify(queryKeys)])

    const handleCancel = () => {
        onCancel();
    }

    const handleSearch = (current: number, pageSize: number) => {
        setLoading(true);
        xhrPostJson(pageApi, {
            pageNo: current,
            pageSize,
            queryKeys
        }).then((res: any) => {
            if (res.success) {
                setDataSource({
                    ...res.result,
                    number: current
                });
            }
        }).finally(() => {
            setLoading(false);
        })
    }

    const initTableColumns = async () => {
        const res: any = await getPageMeta(queryKeys.pageCode);
        const result: any = getMetaSorted(res.result || []);

        setColumns(result.tableColumns || []);
    }

    return (
        <Modal
            title={title}
            width={900}
            className="fileBox-history-modal"
            visible={visible}
            onCancel={handleCancel}
            onOk={handleCancel}
        >
            <TableRenger
                isRequesting={loading}
                metas={columns}
                data={dataSource}
                handleSearch={handleSearch}
            />
        </Modal>
    )
}

export default HistoryModal;
